import _ from 'lodash';
import { groupBy, maxBy, meanBy, minBy, sortBy, sumBy, uniqBy } from 'lodash';
import moment from 'moment';
Date.prototype.format = function (fmt) {
  var o = {
    'M+': this.getMonth() + 1, //月份
    'd+': this.getDate(), //日
    'h+': this.getHours(), //小时
    'm+': this.getMinutes(), //分
    's+': this.getSeconds(), //秒
    'q+': Math.floor((this.getMonth() + 3) / 3), //季度
    'S': this.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + '').substr(4 - RegExp.$1.length),
    );
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length),
      );
  return fmt;
};
function formatTime(date, type) {
  let _format = '';
  switch (type) {
    case '1':
      _format = 'yyyy';
      break;
    case '2':
      _format = 'yyyy-MM';
      break;
    case '3':
      _format = 'yyyy-MM-dd';
      break;
    case '4':
      _format = 'yyyy-MM-dd hh:00';
      break;
    case '5':
      _format = 'yyyy-MM-dd hh:mm';
      break;
    case '6':
      _format = 'yyyy-MM-dd hh:mm:ss';
      break;
  }
  return new Date(date).format(_format);
}
function changeDynamicSeries(options, data) {
  debugger
  if (options.series.length < 1) {
    return options;
  }
  debugger;
			let _data = JSON.parse(JSON.stringify(data));
			let _group_x = options.series[0].encodeTemp['temp_x'];//分组字段--x轴 分类字段
			let _group_y = options.series[0].encodeTemp['temp_y'];//分组字段--y轴 数据字段
			let _newList_x=_.groupBy(_data,(o)=>o[_group_x])//分组字段--X轴
			let _newList_y=[]//数据源---系列
			let _collectDataFieldSelect = options.series[0]['CollectDataIndex'];
			let _collectDataField = options.series[0]['CollectData'];//归集系列指定的字段
			if(_collectDataFieldSelect && _collectDataField){//如果选中了使用归集系列，且指定了字段
				_newList_y=_.groupBy(_data,(o)=>o[_collectDataField])//系列分组后
			}else{
				_newList_y=_.groupBy(_data,(o)=>o[_group_y])//数据源---系列
			}
			let _tempList=[]
			let _Key_x=Object.keys(_newList_x)//x轴需要列
			let _x_obj={}//先弄一个完善的列属性对象
			_Key_x.forEach(item=>{
				_x_obj[item]=0
			})
			let _Key_y=Object.keys(_newList_y)
			_Key_y.forEach(name=>{
				let _tempItem=_.groupBy(_newList_y[name],_group_x)
				let _one={'name':name}
				Object.keys(_tempItem).forEach(_subState=>{
					if(_collectDataFieldSelect && _collectDataField){//如果选中了使用归集系列，且指定了字段
						//_tempItem[_subState]：一个系列>一个类别>下的一个数组集合（也许有多条）
						let _value = changeDataByType(
              _group_y,
              options.series[0]['polymerization'],
              _tempItem[_subState],
            );
						_one[_subState]=_value
					}else{
						_one[_subState]=_tempItem[_subState].length
					}
				})
				let temp=JSON.parse(JSON.stringify(_x_obj))
				_tempList.push(Object.assign(temp,_one))
			})
			//把组织完的数据转成新数组
			let newListHead=['name',..._Key_x]
			let newListBody=[newListHead]
			_tempList.forEach(item=>{
				let _array=[item['name']]
				_Key_x.forEach(subItem=>{
					_array.push(item[subItem])
				})
				newListBody.push(_array)
			})
			options.dataset.source=newListBody
			let _seriseList=[]
			let _serise=options.series[0]
			delete _serise.encode
			//最终把系列都弄出来后，在更新到 series 数组中，这样就动态组织出了 系列集合
			_Key_y.forEach(item=>{
				_seriseList.push(Object.assign({seriesLayoutBy: 'row'},_serise,{name:item}))
			})
			options.series=_seriseList
			return options;
		}
function updateRadarSeries(option) {
    option = JSON.parse(JSON.stringify(option));
    option.radar.indicator = []; //{ name: 'Sales', max: 6500 },

    /**
			 *  data:[{
				  value: [4200, 3000, 20000, 35000, 50000, 18000],
				  name: 'Allocated Budget'
				}]
			 */
    let _list = option.dataset.source;
    let _color = option.color;
    if (_list.length) {
      option.series.forEach((item, index) => {
        let _data = [];
        let _color_one = _color[index % 8];
        if (option.dynamicSeries) {
          debugger
          if (index == 0) {
            let _weidu_x = _list[0];
            let _defaultMaxValue = item.encodeTemp['maxIndicatorValue'] || '';
            _weidu_x.forEach((x_name, index) => {
              if (index != 0) {
                let _x_obj = { name: x_name, min: 0 };
                if (_defaultMaxValue) {
                  _x_obj['max'] = _defaultMaxValue * 1;
                }
                option.radar.indicator.push(_x_obj);
              }
            });
          }
          let _filter_y = _list.filter(value => value[0] == item.name);
          if (_filter_y.length) {
            _filter_y[0].forEach((y_value, index) => {
              if (index != 0) {
                _data.push(y_value);
              }
            });
          }
          item.lineStyle.color = _color_one;
          item.itemStyle.color = _color_one;
        } else {
          _list.forEach(obj => {
            if (index == 0) {
              let _max_field = item.encodeTemp['max'] || '';
              let _defaultMaxValue = item.encodeTemp['maxIndicatorValue'] || '';
              let _x_obj = { name: obj[item.encode.x], min: 0 };
              if (_max_field) {
                _x_obj['max'] = obj[_max_field] * 1;
              } else if (_defaultMaxValue) {
                _x_obj['max'] = _defaultMaxValue * 1;
              }
              option.radar.indicator.push(_x_obj);
            }
            _data.push(obj[item.encode.y]);
          });
          !item.lineStyle.color ? (item.lineStyle.color = _color_one) : '';
          !item.itemStyle.color ? (item.itemStyle.color = _color_one) : '';
        }

        item.data = [{ name: item.name, value: _data }];
      });
    } else {
      option.series.forEach(item => {
        item.data = []; //
      });
  }
    return option;
  }

   export function changeDataByType(field, type, data) {
     let _value = ''; //如果type='',虽然不进行处理，但是x轴相同时，字段应该自动求和
     switch (type) {
       case 'count':
         let _count = _.countBy(data, field); //=》{'A':2,'B':1,'c':1} 返回的是一个对象，记录了每个属性出现的次数
         _value = _.sumBy(
           Object.keys(_count).map(key => {
             return _count[key];
           }),
         );
         break;
       case 'distinctCount':
         let _distinctCount = _.countBy(data, field);
         _value = Object.keys(_distinctCount).length;
         break;
       case '':
       case 'sum':
         _value = _.sumBy(data, field);
         break;
       case 'avg':
         _value = _.meanBy(data, field);
         break;
       case 'max':
         _value = _.maxBy(data, field)[field];
         break;
       case 'min':
         _value = _.minBy(data, field)[field];
         break;
     }
     return _value;
   }
export function parseOption(params) {
  let { option, data, type } = params ?? {};
  // debugger
  if (!data) {
    //新增，没有数据时，模拟数据的处理
      let { source = [] } = option?.dataset ?? {};

      if (Array.isArray(option.series)) {
      } else {
        option.series = [option.series];
      }

      let source_ = [];
      let CollectionData = [];

      //处理动态系列功能 ['pie','funnel','radar'](饼图、漏斗、雷达不进入该流程)
      if (
        option.dynamicSeries == true &&
        option.echartType != 'pie' &&
        option.echartType != 'funnel' &&
        option.echartType != 'radar'
      )
      {
        let _group_x =
          option.echartType == 'strip'
            ? option.series[0].encodeTemp['temp_y']
            : option.series[0].encodeTemp['temp_x']; //分组字段--x轴 分类字段

        //处理时间聚合
        CollectionData = option.dataset.source;
        if (CollectionData.length && option.series[0].encodeTemp['group']) {
          let _group = option.series[0].encodeTemp['group'];
          CollectionData.map(item => {
            let _time = item[_group_x];
            let _value = '';
            if (_group == '7') {
              let _week = moment(_time).week().toString().padStart(2, '0');
              _value = _time.substring(0, 4) + '-' + _week + '周';
            } else if (_group == '8') {
              let _week = moment(_time).week().toString().padStart(2, '0');
              _value = _week + '周';
            } else {
              _value = formatTime(_time, _group);
            }
            item[_group_x] = _value;
          });
        }
        //处理时间聚合
        let _group_y =
          option.echartType == 'strip'
            ? option.series[0].encodeTemp['temp_x']
            : option.series[0].encodeTemp['temp_y']; //分组字段--y轴 数据字段
        let _newList_x = groupBy(CollectionData, _group_x); //分组字段--X轴
        let _newList_y = []; //数据源---系列
        let _collectDataFieldSelect = option.series[0]['CollectDataIndex'];
        let _collectDataField = option.series[0]['CollectData']; //归集系列指定的字段
        if (_collectDataFieldSelect && _collectDataField) {
          //如果选中了使用归集系列，且指定了字段
          _newList_y = groupBy(CollectionData, _collectDataField); //系列分组后
        } else {
          _newList_y = groupBy(CollectionData, _group_y); //数据源---系列
        }
        let _tempList = [];
        let _Key_x = Object.keys(_newList_x); //x轴需要列
        let _x_obj = {}; //先弄一个完善的列属性对象
        _Key_x.forEach(item => {
          _x_obj[item] = 0;
        });
        let _Key_y = Object.keys(_newList_y);
        _Key_y.forEach(name => {
          let _tempItem = groupBy(_newList_y[name], _group_x);
          let _one = { name: name };
          Object.keys(_tempItem).forEach(_subState => {
            if (_collectDataFieldSelect && _collectDataField) {
              //如果选中了使用归集系列，且指定了字段
              //_tempItem[_subState]：一个系列>一个类别>下的一个数组集合（也许有多条）
              let _value = changeDataByType(
                _group_y,
                option.series[0]['polymerization'],
                _tempItem[_subState],
              );
              _one[_subState] = _value;
            } else {
              _one[_subState] = _tempItem[_subState].length;
            }
          });
          let temp = JSON.parse(JSON.stringify(_x_obj));

          _tempList.push(Object.assign(temp, _one));
        });
        //把组织完的数据转成新数组
        let newListHead = ['name', ..._Key_x];
        let newListBody = [newListHead];
        _tempList.forEach(item => {
          let _array = [item['name']];
          _Key_x.forEach(subItem => {
            _array.push(item[subItem]);
          });
          newListBody.push(_array);
        });
        debugger;
        option.dataset.source = newListBody;
        let _seriseList = [];
        let _serise = option.series[0];
        delete _serise.encode;
        //最终把系列都弄出来后，在更新到 series 数组中，这样就动态组织出了 系列集合
        _Key_y.forEach(item => {
          _seriseList.push(
            Object.assign({ seriesLayoutBy: 'row' }, _serise, { name: item }),
          );
        });
        option.series = _seriseList;
        return option;
      }
    //处理动态系列功能
    if (option.dynamicSeries == true && option.echartType == 'radar') {
      debugger
      option = changeDynamicSeries(option, option.dataset.source);
    }
      option.series.forEach((v, i, a) => {
        const {
          polymerization,
          encode,
          encodeTemp = {},
          encodeTemp: { temp_x: x, temp_y: y, group } = {},
          dataSort,
          dataSortY,
        } = v ?? {};
        v.type = type || v.type;

        const y_ = !polymerization ? `${y}` : `${polymerization}_${y}`;
        const x_ = !polymerization ? `${x}` : `${polymerization}_${x}`;
        //处理时间聚合问题
        let _group_x =
          option.echartType == 'strip'
            ? option.series[0].encodeTemp['temp_y']
            : option.series[0].encodeTemp['temp_x']; //分组字段
        CollectionData = option.dataset.source;
        if (CollectionData.length && option.series[0].encodeTemp['group']) {
          let _group = option.series[0].encodeTemp['group'];
          CollectionData.map(item => {
            let _time = item[_group_x];
            let _value = '';
            if (_group == '7') {
              let _week = moment(_time).week().toString().padStart(2, '0');
              _value = _time.substring(0, 4) + '-' + _week + '周';
            } else if (_group == '8') {
              let _week = moment(_time).week().toString().padStart(2, '0');
              _value = _week + '周';
            } else {
              _value = formatTime(_time, _group);
            }
            item[_group_x] = _value;
          });
        }
        //处理时间聚合问题

        const groupData =
          option.echartType == 'strip'
            ? groupBy(CollectionData, y)
            : groupBy(CollectionData, x);

        const factory = {
          count() {
            Object.entries(groupData).forEach(([k, v_], i_, a_) => {
              let o = (source_[i_] ||= { ...(source[i_] ?? {}) });
              if (option.echartType == 'strip') {
                o[y] = k;
                o[x_] = v_?.length ?? 0;
              } else {
                o[x] = k;
                o[y_] = v_?.length ?? 0;
              }
            });
          },
          distinctCount() {
            Object.entries(groupData).forEach(([k, v_], i_, a_) => {
              let o = (source_[i_] ||= { ...(source[i_] ?? {}) });
              if (option.echartType == 'strip') {
                o[y] = k;
                o[x_] = uniqBy(v_, x)?.length ?? 0;
              } else {
                o[x] = k;
                o[y_] = uniqBy(v_, y)?.length ?? 0;
              }
            });
          },
          max() {
            Object.entries(groupData).forEach(([k, v_], i_, a_) => {
              let o = (source_[i_] ||= { ...(source[i_] ?? {}) });
              if (option.echartType == 'strip') {
                o[y] = k;
                o[x_] = maxBy(v_, x)?.[x] ?? 0;
              } else {
                o[x] = k;
                o[y_] = maxBy(v_, y)?.[y] ?? 0;
              }
            });
          },
          min() {
            Object.entries(groupData).forEach(([k, v_], i_, a_) => {
              let o = (source_[i_] ||= { ...(source[i_] ?? {}) });
              if (option.echartType == 'strip') {
                o[y] = k;
                o[x_] = minBy(v_, x)?.[x] ?? 0;
              } else {
                o[x] = k;
                o[y_] = minBy(v_, y)?.[y] ?? 0;
              }
            });
          },
          sum() {
            Object.entries(groupData).forEach(([k, v_], i_, a_) => {
              let o = (source_[i_] ||= { ...(source[i_] ?? {}) });
              if (option.echartType == 'strip') {
                o[y] = k;
                o[x_] = sumBy(v_, x) ?? 0;
              } else {
                o[x] = k;
                o[y_] = sumBy(v_, y) ?? 0;
              }
            });
          },
          avg() {
            Object.entries(groupData).forEach(([k, v_], i_, a_) => {
              let o = (source_[i_] ||= { ...(source[i_] ?? {}) });
              if (option.echartType == 'strip') {
                o[y] = k;
                o[x_] = meanBy(v_, x) ?? 0;
              } else {
                o[x] = k;
                o[y_] = meanBy(v_, y) ?? 0;
              }
            });
          },
        };
        if (!polymerization) {
          factory['sum']?.();
        } else {
          factory[polymerization]?.();
        }

        v.encode ||= encodeTemp;
        if (option.echartType == 'strip') {
          v.encode.x = x_;
          v.encode.y = y;
        } else {
          v.encode.x = x;
          v.encode.y = y_;
        }
      });
      if (!option.dynamicSeries) {
        //动态系列没有排序
        //x轴排序
        let dataSortX = option.series?.[0]?.dataSort;
        if (dataSortX) {
          source_ =
            option.echartType == 'strip'
              ? sortBy(source_, [option.series?.[0]?.encode?.y])
              : sortBy(source_, [option.series?.[0]?.encode?.x]);
          if (dataSortX == -1) {
            source_ = source_.reverse();
          }
        }
        //x轴排序
        let dataSortY = option.series?.[0]?.dataSortY;
        if (dataSortY) {
          source_ =
            option.echartType == 'strip'
              ? sortBy(source_, [option.series?.[0]?.encode?.x])
              : sortBy(source_, [option.series?.[0]?.encode?.y]);
          if (dataSortY == -1) {
            source_ = source_.reverse();
          }
        }
      }

      option.dataset ||= {};

    if (option.echartType == 'radar') {
          if (option.dynamicSeries == true) {
            return updateRadarSeries(option);
          } else {
            option.dataset.source = source_;
            return updateRadarSeries(option);
          }
    } else {
        option.dataset.source = source_;
       console.log('option', option);
      //新增，没有数据时，模拟数据的处理
       return option;
    }

  }

  let { source = [] } = option?.dataset ?? {};

  if (Array.isArray(option.series)) {
  } else {
    option.series = [option.series];
  }

  let source_ = [];
  let CollectionData = [];


  //处理动态系列功能 ['pie','funnel','radar'](饼图、漏斗、雷达不进入该流程)
  if (
    option.dynamicSeries == true &&
    option.echartType != 'pie' &&
    option.echartType != 'funnel' &&
    option.echartType != 'radar'
  )
  {
    let _group_x =
      option.echartType == 'strip'
        ? option.series[0].encodeTemp['temp_y']
        : option.series[0].encodeTemp['temp_x']; //分组字段--x轴 分类字段

    //处理时间聚合
    CollectionData = JSON.parse(JSON.stringify(data));
    if (CollectionData.length && option.series[0].encodeTemp['group']) {
      let _group = option.series[0].encodeTemp['group'];
      CollectionData.map(item => {
        let _time = item[_group_x];
        let _value = '';
        if (_group == '7') {
          let _week = moment(_time).week().toString().padStart(2, '0');
          _value = _time.substring(0, 4) + '-' + _week + '周';
        } else if (_group == '8') {
          let _week = moment(_time).week().toString().padStart(2, '0');
          _value = _week + '周';
        } else {
          _value = formatTime(_time, _group);
        }
        item[_group_x] = _value;
      });
    }
    //处理时间聚合
    let _group_y =
      option.echartType == 'strip'
        ? option.series[0].encodeTemp['temp_x']
        : option.series[0].encodeTemp['temp_y']; //分组字段--y轴 数据字段
    let _newList_x = groupBy(CollectionData, _group_x); //分组字段--X轴
    let _newList_y = []; //数据源---系列
    let _collectDataFieldSelect = option.series[0]['CollectDataIndex'];
    let _collectDataField = option.series[0]['CollectData']; //归集系列指定的字段
    if (_collectDataFieldSelect && _collectDataField) {
      //如果选中了使用归集系列，且指定了字段
      _newList_y = groupBy(CollectionData, _collectDataField); //系列分组后
    } else {
      _newList_y = groupBy(CollectionData, _group_y); //数据源---系列
    }
    let _tempList = [];
    let _Key_x = Object.keys(_newList_x); //x轴需要列
    let _x_obj = {}; //先弄一个完善的列属性对象
    _Key_x.forEach(item => {
      _x_obj[item] = 0;
    });
    let _Key_y = Object.keys(_newList_y);
    _Key_y.forEach(name => {
      let _tempItem = groupBy(_newList_y[name], _group_x);
      let _one = { name: name };
      Object.keys(_tempItem).forEach(_subState => {
        if (_collectDataFieldSelect && _collectDataField) {
          //如果选中了使用归集系列，且指定了字段
          //_tempItem[_subState]：一个系列>一个类别>下的一个数组集合（也许有多条）
          let _value = changeDataByType(
            _group_y,
            option.series[0]['polymerization'],
            _tempItem[_subState],
          );
          _one[_subState] = _value;
        } else {
          _one[_subState] = _tempItem[_subState].length;
        }
      });
      let temp = JSON.parse(JSON.stringify(_x_obj));

      _tempList.push(Object.assign(temp, _one));
    });
    //把组织完的数据转成新数组
    let newListHead = ['name', ..._Key_x];
    let newListBody = [newListHead];
    _tempList.forEach(item => {
      let _array = [item['name']];
      _Key_x.forEach(subItem => {
        _array.push(item[subItem]);
      });
      newListBody.push(_array);
    });
    debugger;
    option.dataset.source = newListBody;
    let _seriseList = [];
    let _serise = option.series[0];
    delete _serise.encode;
    //最终把系列都弄出来后，在更新到 series 数组中，这样就动态组织出了 系列集合
    _Key_y.forEach(item => {
      _seriseList.push(
        Object.assign({ seriesLayoutBy: 'row' }, _serise, { name: item }),
      );
    });
    option.series = _seriseList;
    return option;
  }
  //处理动态系列功能
        if (option.dynamicSeries == true && option.echartType == 'radar') {
          option = changeDynamicSeries(option, data);
          debugger
           console.log(option);
        }
  option.series.forEach((v, i, a) => {
    const {
      polymerization,
      encode,
      encodeTemp = {},
      encodeTemp: { temp_x: x, temp_y: y, group } = {},
      dataSort,
      dataSortY,
    } = v ?? {};
    v.type = type || v.type;

    const y_ = !polymerization ? `${y}` : `${polymerization}_${y}`;
    const x_ = !polymerization ? `${x}` : `${polymerization}_${x}`;
    //处理时间聚合问题
    let _group_x =
      option.echartType == 'strip'
        ? option.series[0].encodeTemp['temp_y']
        : option.series[0].encodeTemp['temp_x']; //分组字段
    CollectionData = JSON.parse(JSON.stringify(data));
    if (CollectionData.length && option.series[0].encodeTemp['group']) {
      let _group = option.series[0].encodeTemp['group'];
      CollectionData.map(item => {
        let _time = item[_group_x];
        let _value = '';
        if (_group == '7') {
          let _week = moment(_time).week().toString().padStart(2, '0');
          _value = _time.substring(0, 4) + '-' + _week + '周';
        } else if (_group == '8') {
          let _week = moment(_time).week().toString().padStart(2, '0');
          _value = _week + '周';
        } else {
          _value = formatTime(_time, _group);
        }
        item[_group_x] = _value;
      });
    }
    //处理时间聚合问题

    const groupData =
      option.echartType == 'strip'
        ? groupBy(CollectionData, y)
        : groupBy(CollectionData, x);

    const factory = {
      count() {
        Object.entries(groupData).forEach(([k, v_], i_, a_) => {
          let o = (source_[i_] ||= { ...(source[i_] ?? {}) });
          if (option.echartType == 'strip') {
            o[y] = k;
            o[x_] = v_?.length ?? 0;
          } else {
            o[x] = k;
            o[y_] = v_?.length ?? 0;
          }
        });
      },
      distinctCount() {
        Object.entries(groupData).forEach(([k, v_], i_, a_) => {
          let o = (source_[i_] ||= { ...(source[i_] ?? {}) });
          if (option.echartType == 'strip') {
            o[y] = k;
            o[x_] = uniqBy(v_, x)?.length ?? 0;
          } else {
            o[x] = k;
            o[y_] = uniqBy(v_, y)?.length ?? 0;
          }
        });
      },
      max() {
        Object.entries(groupData).forEach(([k, v_], i_, a_) => {
          let o = (source_[i_] ||= { ...(source[i_] ?? {}) });
          if (option.echartType == 'strip') {
            o[y] = k;
            o[x_] = maxBy(v_, x)?.[x] ?? 0;
          } else {
            o[x] = k;
            o[y_] = maxBy(v_, y)?.[y] ?? 0;
          }
        });
      },
      min() {
        Object.entries(groupData).forEach(([k, v_], i_, a_) => {
          let o = (source_[i_] ||= { ...(source[i_] ?? {}) });
          if (option.echartType == 'strip') {
            o[y] = k;
            o[x_] = minBy(v_, x)?.[x] ?? 0;
          } else {
            o[x] = k;
            o[y_] = minBy(v_, y)?.[y] ?? 0;
          }
        });
      },
      sum() {
        Object.entries(groupData).forEach(([k, v_], i_, a_) => {
          let o = (source_[i_] ||= { ...(source[i_] ?? {}) });
          if (option.echartType == 'strip') {
            o[y] = k;
            o[x_] = sumBy(v_, x) ?? 0;
          } else {
            o[x] = k;
            o[y_] = sumBy(v_, y) ?? 0;
          }
        });
      },
      avg() {
        Object.entries(groupData).forEach(([k, v_], i_, a_) => {
          let o = (source_[i_] ||= { ...(source[i_] ?? {}) });
          if (option.echartType == 'strip') {
            o[y] = k;
            o[x_] = meanBy(v_, x) ?? 0;
          } else {
            o[x] = k;
            o[y_] = meanBy(v_, y) ?? 0;
          }
        });
      },
    };
    if (!polymerization) {
      factory['sum']?.();
    } else {
      factory[polymerization]?.();
    }

    v.encode ||= encodeTemp;
    if (option.echartType == 'strip') {
      v.encode.x = x_;
      v.encode.y = y;
    } else {
      v.encode.x = x;
      v.encode.y = y_;
    }
  });
  if (!option.dynamicSeries) {
    //动态系列没有排序
    //x轴排序
    let dataSortX = option.series?.[0]?.dataSort;
    if (dataSortX) {
      source_ =
        option.echartType == 'strip'
          ? sortBy(source_, [option.series?.[0]?.encode?.y])
          : sortBy(source_, [option.series?.[0]?.encode?.x]);
      if (dataSortX == -1) {
        source_ = source_.reverse();
      }
    }
    //x轴排序
    let dataSortY = option.series?.[0]?.dataSortY;
    if (dataSortY) {
      source_ =
        option.echartType == 'strip'
          ? sortBy(source_, [option.series?.[0]?.encode?.x])
          : sortBy(source_, [option.series?.[0]?.encode?.y]);
      if (dataSortY == -1) {
        source_ = source_.reverse();
      }
    }
  }

  option.dataset ||= {};
  debugger

  if (option.echartType == 'radar') {
    if (option.dynamicSeries == true) {
      return updateRadarSeries(option);
    } else {
      option.dataset.source = source_;
      return updateRadarSeries(option);
    }

  } else {
    if (option.echartType == 'pie') {
        // 饼图分组NaN问题-wangzhen
        // console.log('pie delete xy', option.series)
        option.series.forEach(serie => {
          delete serie.encode.x;
          delete serie.encode.y;
        })
      }
    option.dataset.source = source_;
 console.log('option', option);
 return option;
  }

}
